package com.yonyougov.devops.cruxcisupport.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES 加密解密
 */
@Slf4j
public class AESUtils {
    private static final String PASSWORD = "CRUX-SECRET-KEY";

    private static final String ALGORITHM = "AES";

    private static final int LENGTH = 128;

    public static String encrypt(String content) {
        try {
            KeyGenerator keyGenerator = getKeyGenerator();
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return Base64.getEncoder().encodeToString(cipher.doFinal(byteContent));
        } catch (Exception e) {
            log.error("{} 加密异常: {}", content, e.getMessage());
        }
        return null;
    }

    public static String decrypt(String content) {
        try {
            byte[] bytes = Base64.getDecoder().decode(content);
            KeyGenerator keyGenerator = getKeyGenerator();
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(bytes));
        } catch (Exception e) {
            log.error("{} 解密异常: {}", content, e.getMessage());
        }
        return null;
    }

    private static KeyGenerator getKeyGenerator() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(LENGTH, new SecureRandom(PASSWORD.getBytes()));
        return keyGenerator;
    }
}
